// 初始化 API 设置
let apiUrl = '';
let apiKey = '';
let model = '';

// 加载保存的设置
document.addEventListener('DOMContentLoaded', () => {
    const savedSettings = JSON.parse(localStorage.getItem('apiSettings') || '{}');
    apiUrl = savedSettings.apiUrl || '';
    apiKey = savedSettings.apiKey || '';
    model = savedSettings.model || '';

    document.getElementById('api-url').value = apiUrl;
    document.getElementById('api-key').value = apiKey;
    document.getElementById('model').value = model;
});

// 应用设置
document.getElementById('apply-settings').addEventListener('click', () => {
    apiUrl = document.getElementById('api-url').value;
    apiKey = document.getElementById('api-key').value;
    model = document.getElementById('model').value;

    localStorage.setItem('apiSettings', JSON.stringify({
        apiUrl,
        apiKey,
        model
    }));
    alert('设置已应用');
});

// 发送消息
document.getElementById('send-button').addEventListener('click', async () => {
    const userInput = document.getElementById('user-input').value;
    if (!userInput) return;

    // 显示用户消息
    const chatHistory = document.getElementById('chat-history');
    const userMessage = document.createElement('div');
    userMessage.classList.add('message', 'user-message');
    userMessage.textContent = userInput;
    chatHistory.appendChild(userMessage);

    // 清空输入框
    document.getElementById('user-input').value = '';

    // 显示加载中消息
    const loadingMessage = document.createElement('div');
    loadingMessage.classList.add('message', 'ai-message', 'loading');
    loadingMessage.textContent = '正在思考...';
    chatHistory.appendChild(loadingMessage);

    try {
        if (!apiUrl || !apiKey || !model) {
            throw new Error('请先应用 API 设置');
        }

        const response = await fetch(`${apiUrl}/chat/completions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify({
                model,
                messages: [
                    {
                        role: 'user',
                        content: userInput
                    }
                ]
            })
        });

        if (!response.ok) {
            throw new Error(`请求失败，状态码: ${response.status}`);
        }

        const data = await response.json();
        const aiMessageContent = data.choices[0].message.content;

        // 移除加载中消息
        loadingMessage.remove();

        // 显示 AI 回复
        const aiMessage = document.createElement('div');
        aiMessage.classList.add('message', 'ai-message');
        aiMessage.textContent = aiMessageContent;
        chatHistory.appendChild(aiMessage);

    } catch (error) {
        // 移除加载中消息
        loadingMessage.remove();

        // 显示错误消息
        const errorMessage = document.createElement('div');
        errorMessage.classList.add('message', 'error-message');
        errorMessage.textContent = `错误: ${error.message}`;
        chatHistory.appendChild(errorMessage);
    }
});

// 添加回车发送消息的功能
document.getElementById('user-input').addEventListener('keydown', function (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        document.getElementById('send-button').click();
    }
});

// 引入 MongoDB 官方驱动
const { MongoClient } = require('mongodb');
// 引入 Mongoose 库
const mongoose = require('mongoose');

console.log('MongoDB 驱动和 Mongoose 库已成功引入');